package com.tusuo.stds.ui.scene;

import android.content.Context;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ModuleList;
import com.tusuo.stds.util.Utils;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(ScenePresenter.class)
class ScenePresenter extends MvpBasePresenter<SceneView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<ModuleList> mGetModuleListSubscriber = null;

    private int mSceneId;

    ScenePresenter(Context context, int sceneId) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);
        mSceneId = sceneId;

        Injector.initScenePresenterComponent().inject(this);
    }

    @Override
    public void attachView(SceneView view) {
        super.attachView(view);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mGetModuleListSubscriber != null) {
            mGetModuleListSubscriber.unsubscribe();
            mGetModuleListSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    void loadData() {
        mGetModuleListSubscriber = new GetModuleListSubscriber();
        // TODO: recycle list
        mApiHelper.getModuleList(mGetModuleListSubscriber, mSceneId);
    }

    private class GetModuleListSubscriber extends Subscriber<ModuleList> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final ModuleList list) {
            if (list.checkState(mContext) && getView() != null) {
                getView().setModuleList(list);
            }
        }
    }
}
